package com.frogs.ucenter.service.daoimpl;

import java.math.BigDecimal;
import java.util.Date;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.frogs.framework.base.dao.BaseDao;
import com.frogs.framework.base.service.daoimpl.BaseServiceImpl;
import com.frogs.framework.exception.BusinessException;
import com.frogs.framework.util.StringUtil;
import com.frogs.system.util.OrderStatusEnum;
import com.frogs.system.web.exception.ServiceOperationException;
import com.frogs.ucenter.dao.UserRechargeAdminUpdateDao;
import com.frogs.ucenter.dao.UserRechargeBalanceDao;
import com.frogs.ucenter.dao.UserRechargeRecordDao;
import com.frogs.ucenter.entity.UserRechargeAdminUpdate;
import com.frogs.ucenter.entity.UserRechargeBalance;
import com.frogs.ucenter.entity.UserRechargeRecord;
import com.frogs.ucenter.service.UserRechargeBalanceService;
import com.frogs.ucenter.util.Constants;

@Transactional(propagation=Propagation.REQUIRED, rollbackFor=Exception.class) 
@Service("userRechargeBalanceService")
public class UserRechargeBalanceServiceImpl extends BaseServiceImpl<UserRechargeBalance> implements UserRechargeBalanceService {
    @Autowired
    private UserRechargeBalanceDao userRechargeBalanceDao;

	@Resource
    private UserRechargeRecordDao userRechargeRecordDao;
	
	@Resource
	private UserRechargeAdminUpdateDao userRechargeAdminUpdateDao;
	
    public UserRechargeBalanceServiceImpl() {
        super();
    }

    public UserRechargeBalanceDao getUserRechargeBalanceDao() {
        return userRechargeBalanceDao;
    }

    /**
     * Don't remove or edit it.
     */
    @Override
    protected BaseDao<UserRechargeBalance> getBaseDao() {
        return userRechargeBalanceDao;
    }

    public void setUserRechargeBalanceDao(UserRechargeBalanceDao userRechargeBalanceDao) {
        this.userRechargeBalanceDao = userRechargeBalanceDao;
    }

	@Override
	public int update(UserRechargeBalance userRechargeBalance,
			BigDecimal newBalance, String updateReason, Integer updateId, Integer userId)
			throws BusinessException {
		BigDecimal balance = new BigDecimal(0);
		//加密余额
		String encryptBalance = StringUtil.md5(userId + newBalance.toString(), Constants.ENCRYPT_BALABCE_KEY);
		if(null != userRechargeBalance){//修改
			//1、判断修改前后金额是否相同
			if(userRechargeBalance.getBalance() != newBalance){
				try {
					//2、判断用户的余额是否正常
					if(this.isValidBalance(userRechargeBalance)){
						balance = newBalance.subtract(userRechargeBalance.getBalance());
						userRechargeBalance.setBalance(newBalance);
						userRechargeBalance.setEncryptBalance(encryptBalance);
						userRechargeBalance.setUpdateDate(new Date());
						userRechargeBalanceDao.update(userRechargeBalance);//修改余额表
					}else{
						throw new ServiceOperationException("当前余额存在异常，请联系客服");
					};
				} catch (Exception e) {
					throw new ServiceOperationException("当前余额存在异常，请联系客服");
				}
			}else{
				throw new BusinessException("balance no charge","设置余额等于原余额，不予修改"); 
			}
		}else{//新增余额表
			userRechargeBalance = new UserRechargeBalance();
			userRechargeBalance.setBalance(newBalance);
			userRechargeBalance.setEncryptBalance(encryptBalance);
			userRechargeBalance.setId(userId);
			userRechargeBalanceDao.insert(userRechargeBalance);
			balance = newBalance;
		}
		//3、添加充值记录表
		UserRechargeRecord userRechargeRecord = new UserRechargeRecord();
		userRechargeRecord.setRechargeFrom("后台调整");
		userRechargeRecord.setRechargeMoney(balance);
		userRechargeRecord.setUserId(userId);
		userRechargeRecord.setStatus(OrderStatusEnum.ORDER_STATUS_YES.getId());
		userRechargeRecordDao.insert(userRechargeRecord);
		//4、登记日志表
		UserRechargeAdminUpdate userRechargeAdminUpdate = new UserRechargeAdminUpdate();
		userRechargeAdminUpdate.setUpdateId(updateId);
		userRechargeAdminUpdate.setUserId(userId);
		userRechargeAdminUpdate.setUpdateReason(updateReason);
		userRechargeAdminUpdate.setUpdateNum(balance);
		userRechargeAdminUpdateDao.insert(userRechargeAdminUpdate);
		return 0;
	}
	
	private boolean isValidBalance(UserRechargeBalance userRechargeBalance) throws Exception {
		BigDecimal balance = userRechargeBalance.getBalance();
		Integer userId = userRechargeBalance.getId();
		String encryptBalance = userRechargeBalance.getEncryptBalance();
		if (!StringUtil.md5(userId + balance.toString(), Constants.ENCRYPT_BALABCE_KEY).equals(encryptBalance)) {
			return false;
		}
		return true;
	}
}